extends Node2D
class_name HealthComponent

const Floating_Text_Scene := preload("uid://bce7srf7edef8")

signal died
signal health_changed(cur_percent:float)


@export var max_health: float = 10
var current_health

func _ready() -> void:
	current_health = max_health
	health_changed.emit(get_health_percent())

func get_health_percent() -> float:
	if max_health <= 0:
		return 0
	return min(current_health / max_health, 1)

func heal(amount: int) -> void:
	damage(-amount)

func damage(damage_amount: float, attacker: Character = null) -> void:

	_apply_damage_direct(damage_amount, attacker)

func _apply_damage_direct(damage_amount: float, attacker: Character = null) -> void:
	"""直接应用伤害（内部方法）"""
	current_health = clamp(current_health - damage_amount, 0, max_health)
	

	
	if damage_amount > 0:
		#var floating_text :Node2D= Floating_Text_Scene.instantiate()
		#Global.main.foreground.add_child(floating_text)
		#var randf_rotation = Mathf.create_randf_offset(30)
		#floating_text.modulate = Color.CRIMSON
		#floating_text.global_position = global_position + Vector2.UP.rotated(randf_rotation) * 16
		#floating_text.rotation = randf_rotation
		#var format_string = "%0.1f"
		#if round(damage_amount) == damage_amount:
			#format_string = "%0.0f"
		#floating_text.start(format_string % damage_amount)
		health_changed.emit(get_health_percent())
	else:
		#var floating_text :Node2D= Floating_Text_Scene.instantiate()
		#Global.main.foreground.add_child(floating_text)
		#var randf_rotation = Mathf.create_randf_offset(30)
		#floating_text.modulate = Color.CHARTREUSE
		#floating_text.global_position = global_position + Vector2.UP.rotated(randf_rotation) * 16
		#floating_text.rotation = randf_rotation
		#var format_string = "%0.1f"
		#if round(damage_amount) == damage_amount:
			#format_string = "%0.0f"
		#floating_text.start(format_string % damage_amount)
		health_changed.emit(get_health_percent())
	
	#Callable(func():
		#if current_health == 0:
			#died.emit()
			#if owner is Player:
				#GameEvents.player_death.emit()
			#owner.queue_free()
	#).call_deferred()
	
